package com.wujiale.javacore.stream;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
import java.util.Optional;

public class OptionalTest {
    public static void main(String[] args) throws IOException {

        System.out.println("args:"+ args);

        File file = new File("");
        String canonicalPath = file.getCanonicalPath();
        Path path = Paths.get(canonicalPath + "/src/main/resources/stream/alice30.txt");
        var contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        // stream create functions test
        List<String> wordList = List.of(contents.split(","));

        Optional<String> optionalValue = wordList.stream().filter(s -> s.contains("fred"))
                .findFirst();
        System.out.println(optionalValue.orElse("No word")+" contains fred");

        Optional<String> optionalString = Optional.empty();
        String result = optionalString.orElse("N/A");
        System.out.println("result:"+result);

        result = optionalString.orElseGet(() -> Locale.getDefault().getDisplayName());
        System.out.println("result" + result);

        try {
            result = optionalString.orElseThrow(IllegalStateException::new);
            System.out.println("result:" + result);
        }catch (Throwable t){
            t.printStackTrace();
            System.out.println("捕获到了状态异常");
        }


    }
}
